<template>
  <view class="payment-container">
    <view class="order-summary">
      <view class="summary-header">
        <text class="title">订单确认</text>
      </view>
      
      <view class="order-info">
        <view class="info-item">
          <text class="label">设备名称</text>
          <text class="value">{{ currentOrder?.deviceName }}</text>
        </view>
        
        <view class="info-item">
          <text class="label">设备位置</text>
          <text class="value">{{ currentDevice?.location }}</text>
        </view>
        
        <view class="info-item">
          <text class="label">订单编号</text>
          <text class="value">{{ currentOrder?.id }}</text>
        </view>
        
        <view class="info-item">
          <text class="label">下单时间</text>
          <text class="value">{{ formatTime(currentOrder?.createdAt) }}</text>
        </view>
        
        <view class="amount-item">
          <text class="label">支付金额</text>
          <text class="amount">¥{{ currentOrder?.amount }}</text>
        </view>
      </view>
    </view>
    
    <view class="payment-methods">
      <view class="methods-header">
        <text class="title">选择支付方式</text>
      </view>
      
      <view class="method-list">
        <view 
          class="method-item" 
          :class="{ active: selectedMethod === 'wechat' }"
          @click="selectMethod('wechat')"
        >
          <u-icon name="weixin-fill" size="40" color="#07c160"></u-icon>
          <text class="method-name">微信支付</text>
          <u-icon 
            v-if="selectedMethod === 'wechat'" 
            name="checkmark-circle-fill" 
            size="30" 
            color="#07c160"
          ></u-icon>
        </view>
        
        <view 
          class="method-item" 
          :class="{ active: selectedMethod === 'alipay' }"
          @click="selectMethod('alipay')"
        >
          <u-icon name="zhifubao" size="40" color="#1677ff"></u-icon>
          <text class="method-name">支付宝</text>
          <u-icon 
            v-if="selectedMethod === 'alipay'" 
            name="checkmark-circle-fill" 
            size="30" 
            color="#1677ff"
          ></u-icon>
        </view>
        
        <view 
          class="method-item" 
          :class="{ active: selectedMethod === 'balance' }"
          @click="selectMethod('balance')"
        >
          <u-icon name="account" size="40" color="#ff9900"></u-icon>
          <text class="method-name">余额支付</text>
          <text class="balance">(余额: ¥{{ userBalance }})</text>
          <u-icon 
            v-if="selectedMethod === 'balance'" 
            name="checkmark-circle-fill" 
            size="30" 
            color="#ff9900"
          ></u-icon>
        </view>
      </view>
    </view>
    
    <view class="payment-footer">
      <u-button 
        type="primary" 
        @click="confirmPayment"
        :disabled="!selectedMethod"
      >
        确认支付 ¥{{ currentOrder?.amount }}
      </u-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useUserStore } from '@/store/user'
import { useDeviceStore } from '@/store/device'
import { usePaymentStore } from '@/store/payment'
import { payOrder, payWithBalance, getUserBalance } from '@/api/payment'

// 用户store
const userStore = useUserStore()

// 设备store
const deviceStore = useDeviceStore()

// 支付store
const paymentStore = usePaymentStore()

// 选中的支付方式
const selectedMethod = ref('')

// 用户余额
const userBalance = ref(0)

// 当前订单
const currentOrder = computed(() => paymentStore.getCurrentOrder)

// 当前设备
const currentDevice = computed(() => 
  currentOrder.value 
    ? deviceStore.getDevices.find(d => d.id === currentOrder.value!.deviceId) 
    : null
)

// 格式化时间
const formatTime = (timeString?: string) => {
  if (!timeString) return ''
  
  const date = new Date(timeString)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 选择支付方式
const selectMethod = (method: string) => {
  selectedMethod.value = method
}

// 确认支付
const confirmPayment = async () => {
  if (!selectedMethod.value) {
    uni.showToast({ title: '请选择支付方式', icon: 'none' })
    return
  }
  
  if (!currentOrder.value) {
    uni.showToast({ title: '订单信息异常', icon: 'none' })
    return
  }
  
  uni.showLoading({ title: '支付中...' })
  
  try {
    let result: any
  
    if (selectedMethod.value === 'balance') {
      // 余额支付
      const res = await payWithBalance(currentOrder.value.id, currentOrder.value.amount)
      result = res.data
    } else {
      // 第三方支付
      const res = await payOrder(currentOrder.value.id, selectedMethod.value)
      result = res.data
    }
    
    if (result.status === 'success') {
      uni.showToast({ title: '支付成功', icon: 'success' })
      
      // 更新订单状态
      paymentStore.updateOrderStatus(currentOrder.value.id, 'paid', new Date().toISOString())
      
      // 更新用户余额（如果是余额支付）
      if (selectedMethod.value === 'balance') {
        userStore.updateBalance(userBalance.value - currentOrder.value.amount)
      }
      
      // 延迟跳转到设备控制页面
      setTimeout(() => {
        uni.redirectTo({
          url: `/pages/device/control?id=${currentOrder.value?.deviceId}`
        })
      }, 1500)
    } else {
      uni.showToast({ title: result.message || '支付失败', icon: 'none' })
    }
  } catch (error) {
    uni.showToast({ title: '支付失败，请重试', icon: 'none' })
  } finally {
    uni.hideLoading()
  }
}

// 获取用户余额
const loadUserBalance = async () => {
  try {
    const res = await getUserBalance()
    if (res.code === 200) {
      userBalance.value = res.data.balance
    }
  } catch (error) {
    console.error('获取用户余额失败', error)
  }
}

onLoad((options) => {
  // 页面加载时的逻辑
  if (options?.orderId) {
    // 根据订单ID获取订单详情
    // 这里简化处理，实际应该调用API获取订单详情
  }
})

onMounted(() => {
  // 加载用户余额
  loadUserBalance()
})
</script>

<style lang="scss" scoped>
.payment-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.order-summary {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05);
}

.summary-header {
  .title {
    font-size: 48rpx;
    font-weight: bold;
    color: #333;
    display: block;
    margin-bottom: 30rpx;
  }
}

.order-info {
  .info-item {
    display: flex;
    justify-content: space-between;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    .label {
      font-size: 28rpx;
      color: #999;
    }
    
    .value {
      font-size: 28rpx;
      color: #333;
    }
    
    &:last-child {
      border-bottom: none;
    }
  }
  
  .amount-item {
    display: flex;
    justify-content: space-between;
    padding: 30rpx 0 0;
    
    .label {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
    }
    
    .amount {
      font-size: 48rpx;
      font-weight: bold;
      color: #ff6600;
    }
  }
}

.payment-methods {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05);
}

.methods-header {
  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    display: block;
    margin-bottom: 30rpx;
  }
}

.method-list {
  .method-item {
    display: flex;
    align-items: center;
    padding: 30rpx;
    border-radius: 10rpx;
    background-color: #f5f5f5;
    margin-bottom: 20rpx;
    cursor: pointer;
    
    &.active {
      background-color: #e6f2ff;
      border: 1rpx solid #007aff;
    }
    
    .method-name {
      flex: 1;
      font-size: 32rpx;
      color: #333;
      margin: 0 20rpx;
    }
    
    .balance {
      font-size: 24rpx;
      color: #999;
      margin-right: 20rpx;
    }
  }
}

.payment-footer {
  padding: 20rpx;
  
  .u-button {
    height: 80rpx;
    font-size: 32rpx;
  }
}
</style>